<?php


namespace App\Console\Commands;


use App\Server\Constants;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use \App\Server\WeatherIndex as WeatherIndexServer;

/**
 * 采集天气数据
 * Class WeatherIndex
 * @package App\Console\Commands
 */
class WeatherIndex extends Command
{

    protected $signature = 'weather-index';

    protected $description = '采集天气数据';

    protected $time = 3600;  //采集间隔时间

    /**
     * @throws \Throwable
     */
    public function handle()
    {
        foreach (Constants::$city as $k => $v) {
            $data = DB::table('weathers')->where(['city' => $k, 'date' => date('Y-m-d', strtotime('+ 2 day'))])->first();
            if (!$data) {
                WeatherIndexServer::grab($k);
                echo 'weather index get success city:' . $v;
                return;
            }
            $updatedAt = strtotime($data->updated_at);
            if ($updatedAt <= time() - $this->time) {
                WeatherIndexServer::grab($k);
                echo 'weather index get success city:' . $v;
                return;
            }
        }
        echo 'weather index get success';
        return;
    }
}
